import express from 'express'
import {body, query} from 'express-validator'
import {createSvgCaptcha} from '../config/svgCaptcha.js'
import { Result} from '../config/Result.js'
import {uploader} from '../config/multer.js'
import {getLogs} from '../utils/index.js'
import {encrypt, compare} from '../utils/bcrypt.js'
import {handleExpressValidate} from '../utils/handleExpressValidate.js'
import {setRedisCaptchaData} from '../utils/redisClient.js'

const router = express.Router()

/**
 * @apiDefine test
 * TEST模块
 */

/**
 * @api {post} /test/upload 上传文件
 * @apiVersion 1.0.0
 * @apiName testUpload
 * @apiGroup test
 * @apiBody {String} name=ares 用户名
 * @apiBody {File} avatar 头像
 * @apiSampleRequest /test/upload
 * @apiUse test
 */
router.post('/upload', uploader.single('avatar'), [body('name').notEmpty().withMessage('用户名不能为空')], (req, res) => {
	if(!handleExpressValidate(req, res)) return;
	res.send(Result.success(null));
})

/**
 * @api {get} /test/encrypt 加密
 * @apiDescription 加密字符串
 * @apiVersion 1.0.0
 * @apiName testEncrypt
 * @apiGroup test
 * @apiQuery {String} code 待加密内容
 * @apiSampleRequest /test/encrypt
 * @apiUse test
 */
router.get('/encrypt', [
	query('code').notEmpty().withMessage('待加密内容不能为空')
], (req, res) => {
	if(!handleExpressValidate(req, res)) return;
	res.send(Result.success(encrypt(req.query.code)));
})

/**
 * @api {get} /test/encrypt-compare 比较明文和密文
 * @apiDescription 比较明文和密文
 * @apiVersion 1.0.0
 * @apiName testEncryptCompare
 * @apiGroup test
 * @apiQuery {String} code 明文
 * @apiQuery {String} hash 密文
 * @apiSampleRequest /test/encrypt-compare
 * @apiUse test
 */
router.get('/encrypt-compare', [
	query('code').notEmpty().withMessage('明文不能为空'),
	query('hash').notEmpty().withMessage('密文不能为空')
], (req, res) => {
	if(!handleExpressValidate(req, res)) return;
	res.send(Result.success(compare(req.query.code, req.query.hash)));
})

/**
 * @api {get} /test/captcha 验证码
 * @apiDescription svg-captcha
 * @apiVersion 1.0.0
 * @apiName testCaptcha
 * @apiGroup test
 * @apiSampleRequest /test/captcha
 * @apiUse test
 */
router.get('/captcha', [], (req, res) => {
	const captcha = createSvgCaptcha();
	const sessionId = req.sessionID
	setRedisCaptchaData(sessionId, captcha.text);
	console.log('验证码', captcha.text)
	res.type('svg');
	res.send(Result.success(captcha.data));
})


/**
 * @api {get} /test/log-render 渲染日志
 * @apiDescription 渲染日志
 * @apiVersion 1.0.0
 * @apiName testLogRender
 * @apiGroup test
 * @apiSampleRequest /test/log-render
 * @apiUse test
 */
router.get('/log-render', (req, res) => {
	res.render('logs',  {
		logs: getLogs()
	})
})



export default router
